package sh.base.aop;


import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk的代理类
 * @author lqq
 * @date 2019/2/20
 */
public class JdkProxy extends AopProxy{

    /**
     *  源对象信息
     */
    private TargetSource targetSource;

    /**
     * 初始化，必须体用两个参数
     * @param targetSource
     * @param methodInterceptor
     */
    JdkProxy(TargetSource targetSource, MethodInterceptor methodInterceptor){
        this.targetSource = targetSource;
        this.methodInterceptor = methodInterceptor;
    }


    ///**
    // * 返回接口的代理对象，这个对象没有什么作用，还需要cglib的代理继续丰富功能
    // * @param daoInterface
    // * @param proxyFacade 统一的调用入口
    // * @param <T>
    // * @return
    // */
    //public <T> T getProxy(Class<T> daoInterface , ProxyFacade proxyFacade){
    //    //this.proxyFacade = proxyFacade;
    //    ////TODO 为什么不能使用泛型数组的初始化
    //    ////Class<T>[] classes = {daoInterface};
    //    //Class<?>[] classes = {daoInterface};
    //    //return (T)Proxy.newProxyInstance(daoInterface.getClassLoader(),classes,new JdkInvocationHandler());
    //    //TODO
    //    return null;
    //}

    private MethodInterceptor getMethodInterceptor(){
        return this.methodInterceptor;
    }

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(targetSource.getInterfaces()[0].getClassLoader(),targetSource.getInterfaces(),new JdkInvocationHandler());
    }

    class JdkInvocationHandler implements InvocationHandler{
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //TODO  这里可通过方法匹配优化，暂时一个一个判断
            //调用MethodInterceptor 中的方法执行拦截
            //调用外部类的属性的方法
            return JdkProxy.this.methodInterceptor.invoke(new ReflectiveMethodInvocation(targetSource.getTarget(),
                    method, args));
            //return proxyFacade.intercept(proxy,method,args,null);
        }
    }

}
